﻿logger = new Logger("genericSearch.js");
log = logger.log;
error = logger.error;

// Constants :
const choosenRate = 0.3;

genericMain = function ()
{
    log("Task : Geniric Search");
    var href = location.href;

    if (isIndexPage())
        setTimeout(onIndex, 1000);
    else if (isSearchPage())
        setTimeout(onSearchResult, 2000);
    else
        msg.send('error', "No Script for this tab : " + href);
};

function onIndex()
{
    log("Current Task : onIndex");
    tasks.searchIt = function (arg)
    {
        log("New Task : search : " + arg.itemKeyword);
        var searchEdit = getSearchEdit();
        searchEdit.value = arg.itemKeyword;
        getSubmitButton().click();
    };
    msg.send("indexOpened", {});
}

function onSearchResult()
{
    var timer = setInterval(check, 100);
    function check()
    {
        if (document.readyState === "complete")
        {
            clearInterval(timer);
            startTask();
        }
    }
    function startTask()
    {
        log("Current Task : onSearchResult");

        tasks.lookupItem = functionWithScript(
            /*"./jquery-2.1.4.min.js",
            doWithScript,*/
            "./Taobao/searchTaobaoHelp.js",
            onSetParams);

        msg.send("searchResultShown");
    }
}

function onSetParams(arg)
{
    log("Current Task : onSetParams");
    if (getSortMethod && arg.sortBy && arg.sortBy !== getSortMethod())
    {
        if (arg.sortBy.search("defaultSort") !== -1)
            getSortByDefaultButton().click();
        else if (arg.sortBy.search("salesSort") !== -1)
            getSortBySalesButton().click();
        else if (arg.sortBy.search("populartySort") !== -1)
            getSortByPolulartyButton().click();
        else
            msg.send('error', "Unknow sort method : " + arg.sortBy);
        waitForLoaded(onSetParams, arg);
        return;
    }
    else if (locationSetted && arg.location && !locationSetted())
    {
        getLocationButton(arg.location).click();
        waitForLoaded(onSetParams, arg);
        return;
    }
    else if (priceSetted && arg.itemLowerPrice && !priceSetted())
    {
        getItemLowerPriceEdit().value = arg.itemLowerPrice;
        getItemHigherPriceEdit().value = arg.itemHigherPrice;
        getSubmitPriceButton().click();

        waitForLoaded(onSetParams, arg);
        return;
    }
    else
    {
        onLookupItem(arg);
    }
}

var secondsPerScreen = 0.05;
function onLookupItem(arg)
{
    arg.itemPrice = arg.itemPrice && arg.itemPrice.toString() || "";
    arg.itemId = arg.itemId && arg.itemId.toString() || "";
    //secondsPerScreen = arg.secondsPerScreen || secondsPerScreen;
    log("Current Task : onLookupItem");

    searchOnePage(0);
    function searchOnePage(nth)
    {
        // Functions
        function searchNextPage()
        {
            if (nth + 1 > arg.maxNextPages)
            {
                msg.send('error', 'max page reached');
                return;
            }
            var currentLocation = location.href;
            nextPageButton().click();
            waitForLoaded(searchOnePage, nth + 1);
        }

        // scrolling to make taobao show all items' information
        window.scrollTo(0, 0);
        smoothScrollTo(document.body.scrollHeight, subSearch, secondsPerScreen);

        // Real search process, called when scrolling is finished
        function subSearch()
        {
            // get tops
            var tops = getTops();
            log("# of tops : " + tops.length);

            // parse tops as items
            var items = {};
            var itemsLength = 0;
            for (var i = 0; i < tops.length; i++)
            {
                var item = parseTop(tops[i]);
                item.keyword = arg ? arg.itemKeyword : undefined;
                if (item.link)
                    items[itemsLength++] = item;
            }
            log("# of item : " + itemsLength);

            // send items to server first
            msg.send("itemsFound", items);

            // iterate all items
            iterate(0);
            function iterate(index)
            {
                // make a iteration, preventing too much recursiving.
                var i;
                for (i = index; i < itemsLength; i++)
                {
                    // register comman commands
                    tasks.updateItem = function updateThisItem()
                    {
                        simulateMouseDownOnObject(getA(item.extra.top));
                        item = parseTop(item.extra.top);
                        item.keyword = arg ? arg.itemKeyword : undefined;
                        msg.send("itemUpdated", item);
                    };
                    tasks.searchNextItem = function searchNextItem()
                    {
                        iterate(i + 1);
                    };
                    tasks.abort = doNothing;

                    // Workflow
                    var item = items[i];
                    if (isTargetItem(item))
                    {
                        // -- On main item

                        // scroll to item
                        scrollToItem(item);

                        // send message to server
                        //log("mainItemFound : ");
                        //log(item);
                        msg.send("mainItemFound", item);

                        // Breaking loop, waiting for server's command
                        break;
                    }
                    else if (Math.random() < choosenRate)
                    {
                        // -- On compare item

                        // scroll to item to server
                        //log("compareItemSelected : ");
                        //log(item);
                        msg.send("compareItemSelected", item);

                        // Breaking loop, waiting for server's command
                        break;
                    }
                }
                if (i >= itemsLength)
                {
                    searchNextPage();
                }
            }
        }
    }
    function isTargetItem(item)
    {
        if (!arg)
            return true;
        // itemTitie
        if (arg.itemTitle && item.title && !existStrings(item.title, stringToKeywords(arg.itemTitle)))
            return false;
        // itemPrice
        if (arg.itemPrice && item.price && !existStrings(item.price, stringToKeywords(arg.itemPrice)))
            return false;
        // item's ShopName
        if (arg.itemShopName && item.shop && !existStrings(item.shop, stringToKeywords(arg.itemShopName)))
            return false;
        // id
        if (arg.itemId && item.id && !existStrings(item.id, stringToKeywords(arg.itemId)))
            return false;
        return true;
    }
}

function scrollToItem(item)
{
    var _top = item.extra.top;

    var _r = _top.getBoundingClientRect();
    var r = {
        left: _r.left,
        top: _r.top += window.scrollY,
        width: _r.width,
        height: _r.height
    };
    window.scrollTo(0, r.top + r.height / 2 - window.innerHeight / 2);
}